package hos.thread.executor;

import java.util.concurrent.Callable;
import java.util.concurrent.Future;

import hos.thread.ThreadOption;

/**
 * <p>Title: ThreadStatic </p>
 * <p>Description: 线程静态方法 </p>
 * <p>Company: www.mapuni.com </p>
 *
 * @author : 蔡俊峰
 * @version : 1.0
 * @date : 2021/12/28 17:11
 */
public final class TS {

    private TS() {
    }


    public static ThreadExecutor run(Runnable runnable) {
        return ThreadExecutor.run(ThreadOption.Job.ON, runnable);
    }

    public static ThreadExecutor run(ThreadOption.Job job, Runnable runnable) {
        return ThreadExecutor.run(job, runnable);
    }

    public static void remove(Runnable runnable) {
        ThreadExecutor.thread().remove(runnable);
    }

    public static boolean isMainThread() {
        return ThreadExecutor.isMainThread();
    }

    /**
     * 运行在工作线程
     *
     * @param runnable 工作线程
     */
    public static void postIo(final Runnable runnable) {
        ThreadExecutor.thread().postIo(runnable);
    }

    /**
     * 运行在工作线程
     *
     * @param runnable 工作线程
     */
    public static void postIo(int priority, final Runnable runnable) {
        ThreadExecutor.thread().postIo(priority, runnable);
    }

    /**
     * 运行在工作线程
     *
     * @param runnable 工作线程
     */
    public static void postOnIo(final Runnable runnable) {
        ThreadExecutor.thread().postOnIo(runnable);
    }

    public static <T> Future<T> submit(Callable<T> task) {
        return ThreadExecutor.thread().submit(task);
    }

    public static <T> Future<T> submit(Runnable task, T result) {
        return ThreadExecutor.thread().submit(task, result);
    }

    public static Future<?> submit(Runnable task) {
        return ThreadExecutor.thread().submit(task);
    }

    public static <T> Future<T> submit(int priority, Runnable task, T result) {
        return ThreadExecutor.thread().submit(priority, task, result);
    }

    public static Future<?> submit(int priority, Runnable task) {
        return ThreadExecutor.thread().submit(priority, task);
    }

    /**
     * 重置线程名并设置UnCaughtExceptionHandler包装回调，以便在发生异常时通知用户
     *
     * @param thread   The thread who should be reset.
     * @param callback a callback to notify user.
     */
    public static void resetThread(Thread thread, final ThreadExceptionCallBack callback) {
        //捕获单个线程的异常
        String name = thread.getName();
        thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                //如果线程出现了异常，则会回调该方法
                if (callback != null) {
                    callback.onError(name, e);
                }
            }
        });
    }

}
